using System;
using System.IO;
using System.Threading.Tasks;
using Shop.Backend.Api.Entity;
using Shop.Backend.Api.Repository;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Shop.Backend.Api.Params;
using System.Collections.Generic;

namespace Shop.Backend.Api.Controllers
{
    [ApiController]
    [Route("[Controller]")]
    public class ImagesController : ControllerBase
    {
        private IHostEnvironment _hostingEnvironment;
        private IRepository<GoodsImages> _imagesIRepository;

        private dynamic PicturePath;
        public ImagesController(
            IHostEnvironment hostingEnvironment,
            IRepository<GoodsImages> imagesIRepository
        )
        {
            _hostingEnvironment = hostingEnvironment;
            _imagesIRepository = imagesIRepository;
        }

        public ActionResult Index()
        {
            //获取或设置包含应用程序内容文件的目录的绝对路径。
            var filesPath = _hostingEnvironment.ContentRootPath;

            //将获取的路径的反斜杠转成斜杠
            PicturePath = filesPath.Replace('\\', '/');

            Console.WriteLine(PicturePath);

            return null;
        }

        [HttpGet]
        public dynamic Getfiles([FromQuery] Pager pager)
        {

            // get请求默认从url中获取参数，如果需要使用实体接收参数，需要FromQuery特性
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;
            var users = _imagesIRepository.Table;

            var u = users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();


            return new
            {
                Code = 1000,
                Data = new { Data = u, Pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                Msg = "获取图片路径成功^_^"
            };
        }

        [HttpGet, Route("get")]
        public dynamic Get()
        {
            var users = _imagesIRepository.Table;

            return new
            {
                Code = 1000,
                Data = users,
                Msg = "获取图片路径成功^_^"
            };
        }



        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var picture = _imagesIRepository.GetById(id);
            return new
            {
                Code = 1000,
                Data = picture,
                Msg = "获取指定图片^_^"
            };
        }


        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {

            _imagesIRepository.Delete(id);
            return new
            {
                Code = 1000,
                Data = "",
                Msg = "删除用户成功^_^"
            };
        }




        [HttpPost, Route("files")]
        public async Task<IActionResult> UploadFiles()
        {
            Index();
            string filesPath = "";

            //Microsoft.AspNetCore.Http.FormFileCollection
            var files = Request.Form.Files;


            //将今天的日期作为相对路径创建一个子文件夹 比如 20210728
            string tempPath = DateTime.Now.ToString("yyyyMMdd");//相对路径

            string physicPath = PicturePath + "/wwwroot/";//物理路径

            //确定给定路径是否引用磁盘上的现有目录。
            if (!Directory.Exists(physicPath))
            {
                //在指定路径中创建所有目录和子目录,除非它们已经存在。 参数:要创建的目录
                Directory.CreateDirectory(physicPath);
            }

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    //新文件名字
                    string filesName = DateTime.Now.ToFileTime() + Path.GetExtension(formFile.FileName);

                    //Combine 拼接路径
                    string FullPath = Path.Combine(physicPath, filesName);

                    //将拼接完的路径中的反斜杠去掉
                    string fileFullPath = FullPath.Replace('\\', '/');

                    using (var stream = new FileStream(fileFullPath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);//保存文件
                    }

                    filesPath += filesName;

                    // var picturesql = new GoodsImages
                    // {

                    //     PictureName = formFile.FileName,
                    //     PicturePath = filesPath,
                    //     status = "不展示"
                    // };
                    // await _imagesIRepository.InsertAsync(picturesql);
                }
            }

            return Ok(new { filesPath });
        }


        [HttpPost, Route("avatar")]
        public async Task<IActionResult> ArticleUploadFiles()
        {

            Index();
            string filesPath = "";

            // var article = _articlesIRepository.GetById(id);

            //Microsoft.AspNetCore.Http.FormFileCollection
            var files = Request.Form.Files;


            //将今天的日期作为相对路径创建一个子文件夹 比如 20210728
            string tempPath = DateTime.Now.ToString("yyyyMMdd");//相对路径

            string physicPath = PicturePath + "/wwwroot/";//物理路径

            //确定给定路径是否引用磁盘上的现有目录。
            if (!Directory.Exists(physicPath))
            {
                //在指定路径中创建所有目录和子目录,除非它们已经存在。 参数:要创建的目录
                Directory.CreateDirectory(physicPath);
            }

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    //新文件名字
                    string filesName = DateTime.Now.ToFileTime() + Path.GetExtension(formFile.FileName);

                    //Combine 拼接路径
                    string FullPath = Path.Combine(physicPath, filesName);

                    //将拼接完的路径中的反斜杠去掉
                    string fileFullPath = FullPath.Replace('\\', '/');

                    using (var stream = new FileStream(fileFullPath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);//保存文件
                    }

                    filesPath += filesName;

                }
            }

            return Ok(new { filesPath });


        }
    }
}